<template>
  <div class="affairs-process">
    <div class="header">
      <router-link to="/main/process" class="back-btn">
        <i class="el-icon-arrow-left"></i>
        <span>返回</span>
      </router-link>
      <h2>行政事务管理</h2>
    </div>

    <div class="content">
      <!-- 流程导航 -->
      <el-tabs v-model="activeTab" type="card">
        <el-tab-pane label="我的申请" name="myApply">
          <div class="operation-bar">
            <el-button type="primary" @click="createAffair">新建事务申请</el-button>
          </div>
          <el-table :data="myApplyList" v-loading="loading">
            <el-table-column prop="affairNo" label="事务编号" width="180"></el-table-column>
            <el-table-column prop="type" label="事务类型" width="120">
              <template slot-scope="scope">
                <el-tag :type="getTypeTag(scope.row.type)">{{ getTypeText(scope.row.type) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="title" label="事务标题"></el-table-column>
            <el-table-column prop="createTime" label="申请时间" width="180">
              <template slot-scope="scope">
                {{ formatDate(scope.row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="120">
              <template slot-scope="scope">
                <el-tag :type="getStatusTag(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" fixed="right">
              <template slot-scope="scope">
                <el-button size="mini" @click="viewDetail(scope.row)">查看</el-button>
                <el-button 
                  size="mini" 
                  type="danger" 
                  v-if="canCancel(scope.row)"
                  @click="cancelApply(scope.row)">撤销</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="待处理事务" name="pending">
          <el-table :data="pendingList" v-loading="loading">
            <el-table-column prop="affairNo" label="事务编号" width="180"></el-table-column>
            <el-table-column prop="type" label="事务类型" width="120">
              <template slot-scope="scope">
                <el-tag :type="getTypeTag(scope.row.type)">{{ getTypeText(scope.row.type) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="title" label="事务标题"></el-table-column>
            <el-table-column prop="applicant" label="申请人" width="120"></el-table-column>
            <el-table-column prop="createTime" label="申请时间" width="180">
              <template slot-scope="scope">
                {{ formatDate(scope.row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" fixed="right">
              <template slot-scope="scope">
                <el-button size="mini" @click="viewDetail(scope.row)">查看</el-button>
                <el-button 
                  size="mini" 
                  type="primary"
                  @click="handleAffair(scope.row)">处理</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="已处理事务" name="handled">
          <el-table :data="handledList" v-loading="loading">
            <el-table-column prop="affairNo" label="事务编号" width="180"></el-table-column>
            <el-table-column prop="type" label="事务类型" width="120">
              <template slot-scope="scope">
                <el-tag :type="getTypeTag(scope.row.type)">{{ getTypeText(scope.row.type) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="title" label="事务标题"></el-table-column>
            <el-table-column prop="applicant" label="申请人" width="120"></el-table-column>
            <el-table-column prop="handleTime" label="处理时间" width="180">
              <template slot-scope="scope">
                {{ formatDate(scope.row.handleTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="120">
              <template slot-scope="scope">
                <el-tag :type="getStatusTag(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" fixed="right">
              <template slot-scope="scope">
                <el-button size="mini" @click="viewDetail(scope.row)">查看</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </div>

    <!-- 新建事务对话框 -->
    <el-dialog title="新建事务申请" :visible.sync="dialogVisible" width="50%">
      <el-form :model="formData" ref="form" :rules="rules" label-width="100px">
        <el-form-item label="事务类型" prop="type">
          <el-select v-model="formData.type" placeholder="请选择事务类型" style="width: 100%">
            <el-option label="办公环境" value="environment"></el-option>
            <el-option label="设备维护" value="equipment"></el-option>
            <el-option label="物品领用" value="supplies"></el-option>
            <el-option label="其他事务" value="other"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="事务标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入事务标题"></el-input>
        </el-form-item>

        <el-form-item label="事务内容" prop="content">
          <el-input
            type="textarea"
            v-model="formData.content"
            :rows="4"
            placeholder="请详细描述事务内容">
          </el-input>
        </el-form-item>

        <el-form-item label="优先级" prop="priority">
          <el-radio-group v-model="formData.priority">
            <el-radio label="high">高</el-radio>
            <el-radio label="medium">中</el-radio>
            <el-radio label="low">低</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="期望完成时间" prop="expectedTime">
          <el-date-picker
            v-model="formData.expectedTime"
            type="datetime"
            placeholder="选择期望完成时间">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="附件">
          <el-upload
            action="/api/file/upload"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            multiple
            :limit="5"
            :file-list="formData.attachments">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">可上传相关文件，单个文件不超过10MB</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">提 交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'AffairsProcess',
  data() {
    return {
      activeTab: 'myApply',
      loading: false,
      myApplyList: [],
      pendingList: [],
      handledList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      formData: {
        type: '',
        title: '',
        content: '',
        priority: 'medium',
        expectedTime: '',
        attachments: []
      },
      rules: {
        type: [{ required: true, message: '请选择事务类型', trigger: 'change' }],
        title: [{ required: true, message: '请输入事务标题', trigger: 'blur' }],
        content: [{ required: true, message: '请输入事务内容', trigger: 'blur' }],
        expectedTime: [{ required: true, message: '请选择期望完成时间', trigger: 'change' }]
      }
    }
  },
  methods: {
    // 获取列表数据
    async fetchList() {
      this.loading = true
      try {
        let res
        const params = {
          page: this.currentPage,
          size: this.pageSize
        }

        switch (this.activeTab) {
          case 'myApply':
            res = await this.$http.get('/api/affairs/my', { params })
            this.myApplyList = res.data.records
            break
          case 'pending':
            res = await this.$http.get('/api/affairs/pending', { params })
            this.pendingList = res.data.records
            break
          case 'handled':
            res = await this.$http.get('/api/affairs/handled', { params })
            this.handledList = res.data.records
            break
        }
        this.total = res.data.total
      } catch (error) {
        this.$message.error('获取列表失败')
      } finally {
        this.loading = false
      }
    },

    // 新建事务
    createAffair() {
      this.dialogVisible = true
      this.formData = {
        type: '',
        title: '',
        content: '',
        priority: 'medium',
        expectedTime: '',
        attachments: []
      }
    },

    // 提交表单
    async submitForm() {
      try {
        await this.$refs.form.validate()
        await this.$http.post('/api/affairs', this.formData)
        this.$message.success('提交成功')
        this.dialogVisible = false
        this.fetchList()
      } catch (error) {
        this.$message.error(error.message || '提交失败')
      }
    },

    // 查看详情
    viewDetail(row) {
      this.$router.push(`/main/xingzheng/affairs/detail/${row.id}`)
    },

    // 处理事务
    handleAffair(row) {
      this.$router.push(`/main/xingzheng/affairs/handle/${row.id}`)
    },

    // 撤销申请
    async cancelApply(row) {
      try {
        await this.$confirm('确定要撤销该申请吗？', '提示', {
          type: 'warning'
        })
        await this.$http.post(`/api/affairs/${row.id}/cancel`)
        this.$message.success('撤销成功')
        this.fetchList()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('撤销失败')
        }
      }
    },

    // 工具方法
    formatDate(date) {
      return this.$moment(date).format('YYYY-MM-DD HH:mm')
    },
    getTypeTag(type) {
      const typeMap = {
        environment: 'success',
        equipment: 'warning',
        supplies: 'info',
        other: ''
      }
      return typeMap[type] || ''
    },
    getTypeText(type) {
      const typeMap = {
        environment: '办公环境',
        equipment: '设备维护',
        supplies: '物品领用',
        other: '其他事务'
      }
      return typeMap[type] || type
    },
    getStatusTag(status) {
      const statusMap = {
        pending: '',
        processing: 'warning',
        completed: 'success',
        cancelled: 'info'
      }
      return statusMap[status] || ''
    },
    getStatusText(status) {
      const statusMap = {
        pending: '待处理',
        processing: '处理中',
        completed: '已完成',
        cancelled: '已撤销'
      }
      return statusMap[status] || status
    },
    canCancel(row) {
      return ['pending'].includes(row.status)
    },

    // 分页方法
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchList()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchList()
    },

    // 文件上传方法
    handlePreview(file) {
      console.log(file)
    },
    handleRemove(file, fileList) {
      this.formData.attachments = fileList
    },
    beforeRemove(file) {
      return this.$confirm(`确定移除 ${file.name}？`)
    }
  },
  watch: {
    activeTab() {
      this.currentPage = 1
      this.fetchList()
    }
  },
  created() {
    this.fetchList()
  }
}
</script>

<style lang="scss" scoped>
.affairs-process {
  padding: 20px;

  .header {
    margin-bottom: 30px;
    position: relative;
    text-align: center;

    .back-btn {
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      text-decoration: none;
      color: #606266;
      display: flex;
      align-items: center;
    }

    h2 {
      margin: 0;
      font-size: 24px;
      color: #303133;
    }
  }

  .content {
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);

    .operation-bar {
      margin-bottom: 20px;
    }
  }

  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }
}
</style> 